<template>
  <!-- 弹出层 -->
  <div class="modal fade cooDeptModal"
       id="cooDeptModal"
       tabindex="-1"
       role="dialog"
       aria-labelledby="myModalLabel"
       aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button"
                  class="close"
                  data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
          <h4 class="modal-title"
              id="myModalLabel">新增/编辑合作机构</h4>
        </div>
        <div class="modal-body">
          <div class="form-horizontal">
            <div class="form-group">
              <label for=""
                     class="col-sm-4 control-label">{{deptFieldName.deptField}}<label style="color: red;">*</label>：</label>
              <div class="col-sm-6">
                <input type="text"
                       id="deartmentName"
                       name="departmentName"
                       v-model="dept.departmentName"
                       class="form-control"
                       placeholder="请输入合作机构名称">
              </div>
            </div>
            <div class="form-group">
              <label for=""
                     class="col-sm-4 control-label">渠道经理：</label>
              <div class="col-sm-6">
                <select class="form-control"
                        v-model="dept.principal"
                        id="principal">
                  <option v-for="partner in partnerList"
                          :value="partner.id">{{partner.accountName}}</option>
                </select>
              </div>
              <!-- <p style="margin-left: 36%;">
							<font color="red">渠道经理需开启相应角色权限后,即可查看其负责机构的报备数据</font>
						</p> -->
            </div>
            <div class="form-group"
                 v-show="deptFieldName.addressShow">
              <label for=""
                     class="col-sm-4 control-label">分销商地址<label style="color: red;">*</label>：</label>
              <div class="col-sm-6">
                <input type="text"
                       id="adress"
                       name="adress"
                       v-model="dept.address"
                       class="form-control"
                       placeholder="请输入分销商地址">
              </div>
            </div>
            <div class="form-group"
                 v-show="deptFieldName.provinceShow">
              <label for=""
                     class="col-sm-4 control-label">省份<label style="color: red;">*</label>：</label>
              <div class="col-sm-6">
                <select class="form-control"
                        v-model="provinceId"
                        id="province">
                  <option v-for="province in provinceList"
                          :value="province.id">{{province.name}}</option>
                </select>
              </div>
            </div>
            <div class="form-group"
                 v-show="deptFieldName.cityShow">
              <label for=""
                     class="col-sm-4 control-label">城市：</label>
              <div class="col-sm-6">
                <select class="form-control"
                        v-model="cityId"
                        id="city">
                  <option v-for="city in cityList"
                          :value="city.id">{{city.name}}</option>
                </select>
              </div>
            </div>
            <div class="form-group"
                 v-if="licenseFlag">
              <label class="col-sm-4 control-label">营业执照：</label>
              <div class="col-sm-6">
                <div id="faceImg2"
                     class="add-huxing over-img"
                     v-if="dept.imgUrl">
                  <img :src="dept.imgUrl"
                       style="position: absolute;left: 0;top: 0;width: 100%;height: 100%;" />
                  <i class="fa fa-times-circle iconDelete"
                     @click="removeImage"></i>
                </div>
                <div class="add-huxing over-img"
                     v-if="!dept.imgUrl">
                  <input type="file"
                         class="file-btn"
                         style="width:100%; "
                         @change="onFileChange">
                  <p style="font-size: 36px;">＋</p>
                  <p>上传图片</p>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button"
                  v-on:click="saveAgentOrg"
                  v-show="btnShow"
                  class="btn checkedBtn">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  //接收父组件的绑定值
  props: ["cooDeptInfo", "modalId"],
  data() {
    return {
      //机构信息对象
      dept: {
        id: this.cooDeptInfo.orgId,
        parentId: this.cooDeptInfo.parentOrgId,
        departmentName: "",
        principal: "",
        address: "",
        province: "",
        city: "",
        imgUrl: ""
      },
      deptFieldName: {
        deptField: "分销商名称",
        addressShow: true,
        provinceShow: true,
        cityShow: true
      },
      provinceList: [],
      provinceId: "",
      cityList: [],
      cityId: "",
      partnerList: [],
      btnShow: true,
      licenseFlag: false
    };
  },
  mounted() {
    this.initProvince();
    this.initPartner();
  },
  watch: {
    //监听父组件绑定值是否改变
    cooDeptInfo: {
      handler: function (val, oldVal) {
        // console.log(val, 77);
        var optType = this.cooDeptInfo.optType;
        var nodeLevel = this.cooDeptInfo.nodeLevel;
        var orgId = this.cooDeptInfo.orgId;
        var parentId = this.cooDeptInfo.parentOrgId;
        if (nodeLevel == 1) {
          this.deptFieldName.addressShow = true;
          this.deptFieldName.provinceShow = true;
          this.deptFieldName.cityShow = true;
          this.deptFieldName.deptField = "分销商名称";
        } else if (2 == nodeLevel || 3 == nodeLevel) {
          this.deptFieldName.addressShow = false;
          this.deptFieldName.provinceShow = false;
          this.deptFieldName.cityShow = false;
          this.deptFieldName.deptField = "门店名称";
          if (3 == nodeLevel) {
            this.deptFieldName.deptField = "组别";
          }
        }
        // 营业执照只有在一级公司才显示
        if (
          val.pId === null ||
          parseInt(val.pId) === val.merchantId ||
          nodeLevel == 1
        ) {
          this.licenseFlag = true;
        } else {
          this.licenseFlag = false;
        }
        this.initOrg();
      },
      //深层监听，当位对象时，若设为true，属性变更时即可触发，若为false，属性无法监听到
      deep: true
    },
    provinceId: function (val, oldVal) {
      this.$nextTick(() => {
        this.initCity();
      });
    }
  },
  methods: {
    //创建文件对象
    onFileChange(e) {
      console.log(e, 77);
      var files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      var size = files[0].size;
      if (size > 3145728) {
        layer.msg("图片大小不能超过3M");
        return;
      }
      var alt = e.target.alt;
      this.createImage(files[0], alt);
    },
    createImage(file, alt) {
      var _self = this;
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (e) {
        _self.ajaxfile(file.name, e.target.result, alt);
      };
    },
    //将base64转换blob
    dataURLtoBlob(dataUrl) {
      var arr = dataUrl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime
      });
    },
    //上传附件
    ajaxfile(fileName, file, alt) {
      layer.load(0, {
        shade: false
      }); //弹出加载层
      var _self = this;
      var myForm = new FormData(); //创建formdata
      var blobBin = _self.dataURLtoBlob(file); //base64转换blob
      myForm.append("blobObject", blobBin); //想formData添加blob数据
      myForm.append("suffix", fileName.substr(fileName.lastIndexOf(".")));
      var url = _self.utilHelper.apiUrl + "/api/uploadBase64ToQiNiu";
      _self.$http.post(url, myForm).then(
        (response) => {
          layer.closeAll("loading"); //关闭加载层
          var data = response.body;
          if (data.result == "1") {
            _self.dept.imgUrl = data.resData.imgName;
          } else {
            layer.msg("图片上传失败，请重试");
          }
        },
        (response) => {
          layer.msg(response);
        }
      );
    },
    removeImage() {
      this.dept.imgUrl = "";
    },
    initProvince: function () {
      var _self = this;
      var body = {};
      body.params = {};
      var url = _self.utilHelper.apiUrl + "/api/getProvince";
      _self.$http.post(url, body).then((response) => {
        var resData = response.body.resData;
        if (resData.result == "1") {
          _self.provinceList = resData.areaList;
        }
      });
    },
    initCity: function () {
      var _self = this;
      var body = {};
      body.params = {
        areaId: _self.provinceId
      };
      var url = _self.utilHelper.apiUrl + "/api/getCity";
      _self.$http.post(url, body).then((response) => {
        var resData = response.body.resData;
        if (
          resData.result == "1" ||
          (resData.areaList && resData.areaList.length > 0)
        ) {
          _self.cityList = resData.areaList;
        }
      });
    },
    initPartner: function () {
      var _self = this;
      var body = {};
      body.params = {
        companyId: ""
      };
      var url = _self.utilHelper.apiUrl + "/api/getPartnerByCompany";
      _self.$http.post(url, body).then((response) => {
        var resData = response.body.resData;
        _self.partnerList = resData.partnerInfoList;
      });
    },
    initOrg() {
      var _self = this;
      var orgId = _self.cooDeptInfo.orgId;
      var optType = _self.cooDeptInfo.optType;
      //存在机构ID,并且为修改操作时,根据ID加载一遍机构数据
      if (orgId && "U" == optType) {
        var params = {};
        params["id"] = orgId;
        var body = {};
        body.params = params;
        var url = _self.utilHelper.apiUrl + "/api/getDeptById";
        _self.$http.post(url, body).then(
          (response) => {
            var resData = response.body.resData;
            var dept = resData.department;
            _self.dept.id = dept.id;
            _self.dept.parentId = dept.parentId;
            _self.dept.departmentName = dept.departmentName;
            _self.dept.principal = dept.principal;
            _self.dept.address = dept.address;
            _self.dept.imgUrl = dept.credential;
            _self.provinceId = dept.province;
            _self.cityId = dept.city;
          },
          (response) => {}
        );
      } else if ("A" == optType) {
        _self.dept.id = "";
        _self.dept.departmentCode = "";
        _self.dept.departmentName = "";
        _self.dept.remark = "";
        //操作类型为新增时，将树节点的ID设为机构的父节点
        _self.dept.parentId = orgId;
      }
    },
    saveAgentOrg() {
      var _self = this;
      var params = {};
      //操作类型为新增时，将机构ID设为空,否则会执行修改操作
      var url = _self.utilHelper.apiUrl + "/api/editAgentDept";
      params.companyName = _self.dept.departmentName;
      params.province = _self.provinceId;
      params.city = _self.cityId;
      params.address = _self.dept.address;
      params.principal = _self.dept.principal;
      params.parentId = _self.cooDeptInfo.parentOrgId;
      params.credentialModelId = _self.modalId;
      params.credentialModelValue = _self.dept.imgUrl;
      if ("A" == _self.cooDeptInfo.optType) {
        url = _self.utilHelper.apiUrl + "/api/addAgentDept";
      } else if ("U" == _self.cooDeptInfo.optType) {
        params.id = _self.dept.id;
      }
      if (_self.orgValidate() == true) {
        var body = {};
        body.params = params;
        _self.btnShow = false;
        _self.$http.post(url, body).then(
          (response) => {
            var resData = response.body.resData;
            var result = resData.result;
            //输出操作信息
            layer.msg(
              resData.resultMsg,
              {
                time: 1000
              },
              function () {
                //关闭弹出层
                _self.btnShow = true;
                if ("1" == result) {
                  $("#cooDeptModal").modal("hide");
                  //子组件向父组件传递信号: 调用父组件中对子组件的监听
                  _self.$emit("cooDeptListener");
                }
              }
            );
          },
          (response) => {}
        );
      }
    },
    orgValidate() {
      var _self = this;
      var departmentName = _self.dept.departmentName;
      if (!departmentName) {
        layer.msg("部门名称不能为空", {
          time: 2000
        });
        return false;
      }
      if (departmentName.length > 20) {
        layer.msg("部门名称过长,限制20个字符", {
          time: 2000
        });
        return false;
      }
      var address = _self.dept.address;
      var addressShow = _self.deptFieldName.addressShow;
      if (addressShow && !address) {
        layer.msg("分销商地址不能为空", {
          time: 2000
        });
        return false;
      }
      var province = _self.provinceId;
      var provinceShow = _self.deptFieldName.provinceShow;
      if (provinceShow && !province) {
        layer.msg("省份不能为空", {
          time: 2000
        });
        return false;
      }
      return true;
    }
  }
};
</script>
<style lang="less">
.cooDeptModal {
  .add-huxing {
    width: 130px !important;
    height: 120px;
    position: relative;
    padding: 15px !important;
    border: 1px dashed #e2e2e2;
    background-color: #fff;
    text-align: center;
    cursor: pointer;
    color: #999;
    display: inline-block;
    margin: 20px 0 50px 0;
    position: relative;
  }
  .over-img {
    margin-left: 10px;
    margin-top: 0px;
  }
  .file-btn {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    outline: none;
    background-color: transparent;
    filter: alpha(opacity=0);
    -moz-opacity: 0;
    -khtml-opacity: 0;
    opacity: 0;
    cursor: pointer;
    z-index: 0;
  }
  .iconDelete {
    position: absolute;
    right: -8px;
    top: -8px;
    font-size: 16px;
    z-index: 9;
  }
}
</style>